<?php

namespace app\api\controller;

use app\common\controller\Api;
use app\common\model\MoneyLog;
use app\common\model\Order;
use app\common\model\Shop as ModelShop;
use think\Log;

/**
 * 服务点接口
 */
class Shop extends Api
{
    protected $noNeedLogin = ['list'];
    protected $noNeedRight = ['*'];

    /**
     * 服务点列表
     *
     */
    public function list()
    {
        $get = request()->get();
        extract($get);

        $list = ModelShop::field(['*', self::distanceSql($lat, $lng)])->where('status', 'normal')->order('distance ASC')->paginate(10);
        $this->success('请求成功', $list);
    }
    /**
     * 获取排序sql
     * @param $latitude
     * @param $longitude
     * @return mixed
     */
    private static function distanceSql($latitude, $longitude)
    {
        $field = "(round(6367000 * 2 * asin(sqrt(pow(sin(((lat * pi()) / 180 - ({$latitude} * pi()) / 180) / 2), 2) + cos(({$latitude} * pi()) / 180) * cos((lat * pi()) / 180) * pow(sin(((lng * pi()) / 180 - ({$longitude} * pi()) / 180) / 2), 2)))/1000,2)) AS distance";
        return $field;
    }

    /**
     * 首页
     *
     */
    public function index()
    {
        $shop = new ModelShop();
        $user = $this->auth->getUserinfo();
        Log::write('用户token:'.$user['token']);
        $data = $shop->get(['id' => $user['shop_id']]);
        $this->success('返回成功', $data);
    }
    /**
     * 服务点信息修改
     *
     */
    public function edit()
    {
        if (!request()->isPost()) {
            $this->error('提交方式错误');
        }
        $post = request()->post();
        extract($post);
        $shop = new ModelShop();
        $user = $this->auth->getUserinfo();
        $shop = $shop->get(['id' => $user['shop_id']]);
        $res  = $shop->allowField(true)->save(['json' => json_encode($post), 'state' => '0']);
        if ($res) {
            $this->success('修改成功');
        }
        $this->error('修改失败');
    }
    /**
     * 服务点统计
     *
     */
    public function statistics()
    {
        $shop = new ModelShop();
        $user = $this->auth->getUserinfo();
        $shop = $shop->get(['id' => $user['shop_id']]);
        $data['today_num'] = Order::where('shop_id', $shop['id'])->whereTime('taketime', 'today')->count();
        $data['yesterday_num'] = Order::where('shop_id', $shop['id'])->whereTime('taketime', 'yesterday')->count();
        $data['money_revenue']  = bcmul($data['today_num'], config('site.service_commission'), 2);
        $data['yesterday_revenue']  = bcmul($data['yesterday_num'], config('site.service_commission'), 2);
        $this->success('', $data);
    }
    /**
     * 余额明细
     *
     */
    public function commission_income()
    {
        $get = request()->get();
        extract($get);
        if (!isset($type) || empty($type)) {
            $this->error('参数错误');
        }
        $moneyLog = new MoneyLog();
        $list = $moneyLog->getList($type, $status ?? 0, $this->auth->id);
        $this->success('', $list);
    }
}
